package com.molichuxing.gateway.api.services.impl;

import com.molichuxing.framework.dto.UploadFileRequestDto;
import com.molichuxing.framework.dto.UploadFileResponseDto;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.UploadUtil;
import com.molichuxing.gateway.api.services.BasicApiService;
import com.molichuxing.gateway.bff.basic.entity.response.*;
import com.molichuxing.gateway.bff.basic.services.BasicBffService;
import com.molichuxing.gateway.bff.basic.services.FileStorageBffService;
import com.molichuxing.gateway.bff.basic.services.VehicleBffService;
import com.molichuxing.gateway.bff.basic.services.VersionBffService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * 基础数据相关接口
 *
 * @author zhaopenghui
 * @date 2019年9月18日
 */
@RestController
@RequestMapping(value = "/basic")
@Api(tags = "基础数据")
public class BasicApiServiceImpl extends RootApiService implements BasicApiService {
    private static final Logger logger = LoggerFactory.getLogger(BasicApiServiceImpl.class);


    @Resource
    BasicBffService basicBffService;

    @Resource
    VehicleBffService vehicleBffService;

    @Resource
    VersionBffService versionBffService;
    
    @Resource
	private FileStorageBffService fileStorageBffService;

    @Override
    @ApiOperation(value = "获取城市")
    @GetMapping(value = "/dealer/city")
    public ResponseResult<List<CityInitialVo>> getRegionList() {
        ResponseResult<List<CityInitialVo>> result = new ResponseResult<>();
        try {

            return result.success(basicBffService.getRegionList());
        } catch (BizException e) {
            logger.error("[getRegionList]获取城市异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getRegionList]获取城市异常", e);
            result.error("获取城市异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "根据车型id详细配置参数")
    @ApiImplicitParam(name = "modelId", value = "车型id", required = true, dataType = "Integer")
    @GetMapping(value = "/vehicle/conf/param")
    public ResponseResult<List<CarBaseConfVo>> findCarModelParamByModelId(@RequestParam  Integer modelId) {
        ResponseResult<List<CarBaseConfVo>> result = new ResponseResult<>();
        try {
            return result.success(vehicleBffService.findCarModelParamByModelId(modelId));
        } catch (BizException e) {
            logger.error("[findCarModelParamByModelId]根据车型id详细配置参数异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[findCarModelParamByModelId]根据车型id详细配置参数异常", e);
            result.error("根据车型id详细配置参数异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取App新版本")
    @GetMapping(value = "/app/version/new")
    public ResponseResult<VersionMobileVo> getNewestMobile(
            @RequestHeader(value = "appVersion") String appVersion,
            @RequestHeader(value = "channel") String channel) {
        ResponseResult<VersionMobileVo> result = new ResponseResult<>();
        try {
            return result.success(versionBffService.getNewestMobile(appVersion, channel));
        } catch (BizException e) {
            logger.error("[getNewestMobile]获取App新版本异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getNewestMobile]获取App新版本异常", e);
            result.error("获取App新版本异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取大屏新版本")
    @GetMapping(value = "/device/version/new")
    public ResponseResult<TerminalUpgradedVo> findUpgradeInfo(
            @RequestHeader(value = "appVersion") String appVersion,
            @RequestHeader(value = "deviceNum") String deviceNum,
            @RequestHeader(value = "chaVersion") String chaVersion,
            @RequestHeader(value = "opVersion") String opVersion) {
        ResponseResult<TerminalUpgradedVo> result = new ResponseResult<>();
        try {
            return result.success(versionBffService.findUpgradeInfo(appVersion, deviceNum, chaVersion, opVersion));
        } catch (BizException e) {
            logger.error("[findUpgradeInfo]获取大屏新版本异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[findUpgradeInfo]获取大屏新版本异常", e);
            result.error("获取App新版本异常");
        }
        return result;
    }
    
	@Override
	@ApiOperation(value = "文件上传-单个")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "type", value = "文件类型（user：用户，dealer：经销商，vehicle：车辆，"
					+ "advertising：广告，accident：事故，maintenance：保养，check：车辆检验，contract：合同，invoice：发票，"
					+ "finance：财务）", required = true, dataType = "String") })
	@PostMapping(value = "/upload/{type}")
	public ResponseResult<UploadFileResponseDto> uploadFile(HttpServletRequest request, MultipartFile file,
			@PathVariable("type") String type) {
        ResponseResult<UploadFileResponseDto> result = new ResponseResult<>();
        try {
            // 查询文件存储配置
            UploadFileRequestDto uploadFileRequestDto = fileStorageBffService.getFileStorageConfig(type);
            if (uploadFileRequestDto == null) {
                result.error(ResponseCodeEnum.UPLOAD_ERROR.getCode(), "文件上传失败,不存在的文件类型");
            }

            UploadFileResponseDto uploadFileResponseDto = UploadUtil.uploadFileToAll(file, uploadFileRequestDto);
            if (uploadFileResponseDto == null) {
                result.error(ResponseCodeEnum.ABNORMAL_ERROR.getCode(), "文件上传失败,文件为空");
            } else {
                result.success(uploadFileResponseDto);
            }
        } catch (BizException e) {
            logger.error("[uploadFile]文件上传异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[uploadFile]文件上传异常", e);
            result.error(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "文件上传失败");
        }

        return result;
    }

    @Override
    @ApiOperation(value = "文件上传-批量")
    @ApiImplicitParams({@ApiImplicitParam(name = "type", value = "文件类型（user：用户，dealer：经销商，vehicle：车辆，"
            + "advertising：广告，accident：事故，maintenance：保养，check：车辆检验，contract：合同，invoice：发票，"
            + "finance：财务）", required = true, dataType = "String")})
    @PostMapping(value = "/upload/{type}/batch")
    public ResponseResult<List<UploadFileResponseDto>> uploadFileBatch(HttpServletRequest request,
                                                                       MultipartFile[] files, @PathVariable("type") String type) {
        ResponseResult<List<UploadFileResponseDto>> result = new ResponseResult<>();
        try {
            // 查询文件存储配置
            UploadFileRequestDto uploadFileRequestDto = fileStorageBffService.getFileStorageConfig(type);
            if (uploadFileRequestDto == null) {
                result.error(ResponseCodeEnum.UPLOAD_ERROR.getCode(), "文件上传失败,不存在的文件类型");
            }
            if (files.length == 1) {
                result.success(Arrays.asList(UploadUtil.uploadFileToAll(files[0], uploadFileRequestDto)));
            } else {
                result.success(UploadUtil.uploadFileBatchToAll(files, uploadFileRequestDto));
            }
        } catch (BizException e) {
            logger.error("[uploadFileBatch]文件批量上传异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[uploadFileBatch]文件批量上传异常", e);
            result.error(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "文件批量上传失败");
        }

        return result;
    }

    @Override
    @ApiOperation(value = "获取省市区父子级关系")
    @ApiImplicitParam(name = "level", value = "等级，不传表示所有，1：省，2：市，3：区", dataType = "Integer")
    @GetMapping(value = "/region/getallcity")
    public ResponseResult<List<RegionCityVo>> getAllCity(@RequestParam(required = false) Integer level) {
        ResponseResult<List<RegionCityVo>> result = new ResponseResult<>();
        try {
            return result.success(basicBffService.getAllCity(level));
        } catch (Exception e) {
            logger.error("[getAllCity]获取省市区父子级别信息异常", e);
            result.error("获取省市区父子级别信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "通过车型id获取提车单参数")

    @ApiImplicitParams({ @ApiImplicitParam(name = "modelId", value = "车型id", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "orderCode", value = "订单号", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "carId", value = "车辆id", required = true, dataType = "Integer")})
    @GetMapping(value = "/delivery/getDeliveryParamDicByModelId")
    public ResponseResult<VehicleDeliveryVo> getDeliveryParamDicByModelId(@RequestParam Integer modelId,@RequestParam Long orderCode,@RequestParam Integer carId) {
         ResponseResult<VehicleDeliveryVo> result = new ResponseResult<>();
         try {
             VehicleDeliveryVo dataList = basicBffService.getDeliveryParamDicByModelId(modelId,orderCode,carId);
             return result.success(dataList);
         } catch (BizException e) {
             logger.error("[getDeliveryParamDicByModelId]通过车型id获取提车单参数", e);
             result.error(e.getExceptionCode(), e.getMessage());
         } catch (Exception e) {
            logger.error(e.getMessage(), e);
             result.error("失败");
         }
         return result;
    }


}
